package cn.v2tila.rsosa.management.service.serviceImpl;

import cn.v2tila.rsosa.management.entity.AssoEntity;
import cn.v2tila.rsosa.management.jpa.AssoJPA;
import cn.v2tila.rsosa.management.service.AssoService;
import cn.v2tila.rsosa.management.utils.PageDataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author v2tila on 23:32 2019/4/17
 */
@Service
public class AssoServiceImpl implements AssoService {
    @Autowired
    private AssoJPA assoJPA;

    @Override
    public PageDataResult getAsso(int page, int limit, AssoEntity assoEntity) {
        PageDataResult pageDataResult = new PageDataResult();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        ExampleMatcher matcher;

        if(assoEntity.getId()==0){
            matcher = ExampleMatcher.matching()
                    .withMatcher("uniqueId", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withIgnorePaths("id");
        }else{
            matcher = ExampleMatcher.matching();
        }
        Example<AssoEntity> example = Example.of(assoEntity,matcher);
        Page<AssoEntity> pages = assoJPA.findAll(example,pageable);
        List<AssoEntity> assoEntityList = pages.getContent();
        int count = assoJPA.findAll(example).size();
        pageDataResult.setData(assoEntityList);
        pageDataResult.setCount(count);
        return pageDataResult;
    }

    @Override
    public boolean existsByNo(String no) {
        return assoJPA.existsByNo(no);
    }

    @Override
    public AssoEntity saveAndFlush(AssoEntity assoEntity) {
        return assoJPA.saveAndFlush(assoEntity);
    }

    @Override
    public void deleteById(Integer id) {
        assoJPA.deleteById(id);
    }

    @Override
    public AssoEntity findByUniqueId(String uniqueId) {
        return assoJPA.findByUniqueId(uniqueId);
    }

    @Override
    public AssoEntity findById(Integer id) {
        Optional<AssoEntity> findResult = assoJPA.findById(id);
        return findResult.get();
    }


}
